const {saveRemoteGold} = require("./custom_loading")

function getCheckpointList() {
  const list = wx.getStorageSync('checkpoints')
  // console.log('get checkpoint', list)
  return list
}

function saveCheckpointList(list) {
  // console.log('save checkpoint', list)
  wx.setStorageSync('checkpoints', list)
}

function getCheckpointByID(checkpoint_list, id) {
  for (let index = 0; index < checkpoint_list.length; index++) {
    if (checkpoint_list[index].code === id) {
      return checkpoint_list[index]
    }
  }
}

function doTaskOperation(checkpoint_list, operation_list) {
  const operations = operation_list.split(';')

  let gold = 0
  let value = 0
  
  console.log('operations', operations)
  for (let index = 0; index < operations.length; index++) {
    let operation = operations[index]
    console.log('operation', operation)
    if (operation.length == 0) {
      continue
    }

    // 检查命令
    const fword = operation.slice(0, 1)
    switch (fword) {
      case '+': // 增加金币
        gold = wx.getStorageSync('gold')
        value = Number(operation.slice(1))
        wx.setStorageSync('gold', gold + value)

        // 保存到远程
        saveRemoteGold();
        break

      case '-': // 减少金币
        gold = wx.getStorageSync('gold')
        value = Number(operation.slice(1))
        gold - value > 0 ? wx.setStorageSync('gold', gold - value) : wx.setStorageSync('gold', 0)

        // 保存到远程
        saveRemoteGold();
        break

      case 'S': // 启动任务（可以通过定位显示任务）
        value = Number(operation.slice(1))
        checkpoint_list.forEach(checkpoint => {
          if (checkpoint.code == value) {
            // console.log('enable checkpoint', checkpoint)
            checkpoint.enable = true
            checkpoint.group = 'MAIN'
          }
        });

        // 保存到本地
        saveCheckpointList(checkpoint_list)
        break

      case 'H': // 隐藏任务（同时不能定位）
        value = Number(operation.slice(1))
        checkpoint_list.forEach(checkpoint => {
          if (checkpoint.code == value) {
            // console.log('hide checkpoint', checkpoint)
            checkpoint.display = false
            checkpoint.enable = false
          }
        });

        // 保存到本地
        saveCheckpointList(checkpoint_list)
        break


      case 'K': // 创建随机密码
        // value = Number(operation.slice(1))
        // console.log('create key', value)
        let keyword = ''
        for (let i = 0; i < 3; i++) {
          let c = Math.floor(Math.random() * 10)
          keyword += c.toString()
        }
        // console.log(keyword)
        wx.setStorageSync(operation, keyword)
        break
    }
  }
}

module.exports = {
  getCheckpointList,
  saveCheckpointList,
  getCheckpointByID,
  doTaskOperation
}
